package com.lktx.sso.admin.service;

import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hutool.core.util.StrUtil;
import com.lktx.sso.admin.dto.AddUserGroupMappingDTO;
import com.lktx.sso.admin.dto.UserGroupMappingDTO;
import com.lktx.sso.admin.entity.SsoOrganization;
import com.lktx.sso.admin.entity.SsoUser;
import com.lktx.sso.admin.entity.SsoUserGroupMapping;
import com.lktx.sso.admin.entity.table.SsoOrganizationTableDef;
import com.lktx.sso.admin.entity.table.SsoUserGroupMappingTableDef;
import com.lktx.sso.admin.entity.table.SsoUserGroupTableDef;
import com.lktx.sso.admin.entity.table.SsoUserTableDef;
import com.lktx.sso.admin.mapper.SsoUserGroupMappingMapper;
import com.lktx.sso.admin.vo.UserGroupMappingVO;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

import static com.lktx.sso.system.entity.table.RoleTableDef.ROLE;

/**
 * 用户组关系映射表 服务类
 *
 */
@Slf4j
@Bean
public class SsoUserGroupMappingService {

    @Autowired
    private SsoUserGroupMappingMapper mapper;

    /**
     * 分页查询列表
     *
     * @param page   分页对象
     * @param userGroupMappingDTO 查询实体
     * @return 所有数据
     */
    public Page<UserGroupMappingVO> page(Page<UserGroupMappingVO> page, UserGroupMappingDTO userGroupMappingDTO) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(SsoUserGroupMappingTableDef.SSO_USER_GROUP_MAPPING.SSO_USER_ID,SsoUserTableDef.SSO_USER.AVATAR
                        ,SsoUserTableDef.SSO_USER.NAME,SsoUserTableDef.SSO_USER.NICKNAME,SsoUserTableDef.SSO_USER.USERNAME,
                        SsoUserTableDef.SSO_USER.PHONE,SsoUserTableDef.SSO_USER.EMAIL,SsoUserTableDef.SSO_USER.REMARK,
                        SsoUserGroupMappingTableDef.SSO_USER_GROUP_MAPPING.CREATE_TIME, SsoOrganizationTableDef.SSO_ORGANIZATION.NAME.as("ssoOrganizationName")
                )
                .from(SsoUserGroupMappingTableDef.SSO_USER_GROUP_MAPPING.as("g"))
                .leftJoin(SsoUserTableDef.SSO_USER).as("u").on(SsoUserGroupMappingTableDef.SSO_USER_GROUP_MAPPING.SSO_USER_ID.eq(SsoUserTableDef.SSO_USER.SSO_USER_ID))
                .leftJoin(SsoOrganizationTableDef.SSO_ORGANIZATION).as("o").on(SsoOrganizationTableDef.SSO_ORGANIZATION.SSO_ORGANIZATION_ID.eq(SsoUserTableDef.SSO_USER.SSO_ORGANIZATION_ID))
                .where(w->{
                            w.eq(SsoUserGroupMapping::getSsoUserGroupId, userGroupMappingDTO.getSsoUserGroupId())
                                    .and(k-> {
                                        k.or(r -> {
                                            r.like(SsoUser::getName, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                        });
                                        k.or(r -> {
                                            r.like(SsoUser::getRemark, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                        });
                                        k.or(r -> {
                                            r.like(SsoUser::getEmail, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                        });
                                        k.or(r -> {
                                            r.like(SsoUser::getNickname, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                        });
                                        k.or(r -> {
                                            r.like(SsoUser::getUsername, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                        });
                                        k.or(r -> {
                                            r.like(SsoUser::getPhone, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                        });
                                    });
                })
                .orderBy(SsoUserGroupMapping::getCreateTime,false);
       return mapper.paginateAs(page,queryWrapper, UserGroupMappingVO.class);

    }

    /**
     * 不分页查询列表
     *
     * @param entity 实体对象
     * @return 查询结果
     */
    public List<SsoUserGroupMapping> list(SsoUserGroupMapping entity) {
        return mapper.selectListByQuery(new QueryWrapper()
                .orderBy(SsoUserGroupMapping::getId,false)
        );
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    public SsoUserGroupMapping getById(Integer id) {
        return mapper.selectOneById(id);
    }


    /**
     * 新增单条数据
     *
     * @param entity 实体对象
     */

    public void save(AddUserGroupMappingDTO entity) {
        List<SsoUserGroupMapping> data=new ArrayList<>();
        for (Integer ssoUserId : entity.getSsoUserIds()) {
            SsoUserGroupMapping ssoUserGroupMapping = new SsoUserGroupMapping();
            ssoUserGroupMapping.setSsoUserId(ssoUserId);
            ssoUserGroupMapping.setSsoUserGroupId(entity.getSsoUserGroupId());
            data.add(ssoUserGroupMapping);
        }
        Db.tx(() -> {
            mapper.insertBatch(data);
            return true;
        });
    }

    /**
     * 修改单条数据
     *
     * @param entity 实体对象
     */
    public void update(SsoUserGroupMapping entity) {
        mapper.update(entity);
    }

    /**
     * 批量删除数据
     *
     * @param addUserGroupMappingDTO 主键集合
     */
    public void deleteByIds(AddUserGroupMappingDTO addUserGroupMappingDTO) {
        if (addUserGroupMappingDTO.getSsoUserIds()==null||addUserGroupMappingDTO.getSsoUserIds().isEmpty()) {
            return;
        }
        mapper.deleteByQuery(QueryWrapper.create()
                .eq(SsoUserGroupMapping::getSsoUserGroupId, addUserGroupMappingDTO.getSsoUserGroupId())
                .in(SsoUserGroupMapping::getSsoUserId, addUserGroupMappingDTO.getSsoUserIds())
        );
    }

    /**
     * 查询不在当前分组的用户
     * @param page
     * @param userGroupMappingDTO
     * @return
     */
    public Page<?> pageUser(Page<UserGroupMappingVO> page, UserGroupMappingDTO userGroupMappingDTO) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(SsoUserTableDef.SSO_USER.SSO_USER_ID,SsoUserTableDef.SSO_USER.AVATAR
                        ,SsoUserTableDef.SSO_USER.NAME,SsoUserTableDef.SSO_USER.NICKNAME,SsoUserTableDef.SSO_USER.USERNAME,
                        SsoUserTableDef.SSO_USER.PHONE,SsoUserTableDef.SSO_USER.EMAIL,SsoUserTableDef.SSO_USER.REMARK,
                        SsoUserGroupMappingTableDef.SSO_USER_GROUP_MAPPING.CREATE_TIME, SsoOrganizationTableDef.SSO_ORGANIZATION.NAME.as("ssoOrganizationName")
                )
                .from(SsoUserTableDef.SSO_USER.as("u"))
                .leftJoin(SsoUserGroupMappingTableDef.SSO_USER_GROUP_MAPPING).as("m")
                .on(SsoUserGroupMappingTableDef.SSO_USER_GROUP_MAPPING.SSO_USER_ID.eq(SsoUserTableDef.SSO_USER.SSO_USER_ID).and(SsoUserGroupMappingTableDef.SSO_USER_GROUP_MAPPING.SSO_USER_GROUP_ID.eq(userGroupMappingDTO.getSsoUserGroupId())))
                .leftJoin(SsoOrganizationTableDef.SSO_ORGANIZATION).as("o").on(SsoOrganizationTableDef.SSO_ORGANIZATION.SSO_ORGANIZATION_ID.eq(SsoUserTableDef.SSO_USER.SSO_ORGANIZATION_ID))
                .where(w->{
                    w.isNull(SsoUserGroupMapping::getSsoUserId)
                            .and(k-> {
                                k.or(r -> {
                                    r.like(SsoUser::getName, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                });
                                k.or(r -> {
                                    r.like(SsoUser::getRemark, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                });
                                k.or(r -> {
                                    r.like(SsoUser::getEmail, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                });
                                k.or(r -> {
                                    r.like(SsoUser::getNickname, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                });
                                k.or(r -> {
                                    r.like(SsoUser::getUsername, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                });
                                k.or(r -> {
                                    r.like(SsoUser::getPhone, userGroupMappingDTO.getKeyword(), StrUtil.isNotEmpty(userGroupMappingDTO.getKeyword()));
                                });
                            });
                })
                .orderBy(SsoUserGroupMapping::getCreateTime,false);
        return mapper.paginateAs(page,queryWrapper, UserGroupMappingVO.class);
    }
}